const userModel = require('../modules/user')
const checkModel = require('../modules/checktimemodules')
const leaveModel = require('../modules/leavemodules')
const overTimeModel = require('../modules/overtimemodules')
const forgetModel = require('../modules/forgetmodules')
const uuid= require('uuid')
const xlsx= require ('node-xlsx');
const path =require('path');
class userController {
    /**
     * 创建用户
     * @param ctx
     * @returns {Promise.<void>}
     */
    static async create(ctx) {
        // 接收客服端
        let req = ctx.req.body;
        if(ctx.req.file&&ctx.req.file.path){
            var str=ctx.req.file.path;
            req.iconUrl=str.substring(str.indexOf("\\"));
        }
        if (req.username 
            && req.loginname 
            && req.password 
            && req.phone 
        ) {
            try {
                // 创建文章模型
                const ret = await userModel.createUser(req);
                // 把刚刚新建的文章ID查询文章详情，且返回新创建的文章信息
               // const data = await userModel.getArticleDetail(ret.id);
                ctx.response.status = 200;
                ctx.body = {
                    code: 200,
                    msg: '创建用户成功',
                    ret
                }

            } catch (err) {
                ctx.response.status = 412;
                ctx.body = {
                    code: 200,
                    msg: '创建用户失败',
                    data: err
                }
            }
        } else {
            ctx.response.status = 416;
            ctx.body = {
                code: 200,
                msg: '参数不齐全',
            }
        }

    }

    static async getalluser(ctx){
      try{
        let data= await userModel.getAllUser();
        ctx.response.status = 200;
                ctx.body = {
                    code: 200,
                    msg: '获取用户列表成功',
                    data
                }
      }catch(err){
        ctx.response.status = 412;
        ctx.body = {
            code: 412,
            msg: '获取用户列表失败',
            err
        }
      }
    }
    
    static async userlogin(ctx,next){
        //console.log("-----------body-----",ctx.request.body);
        //inituserdata();
        let req = ctx.request.body;
        if(req.username&&req.password){
            try{
                let data= await userModel.getUserByLoginName(req.username);
                if(data&&data.password==req.password){
                    ctx.response.status = 200;
                    ctx.body = {
                        code: 200,
                        msg: '获取用户成功',
                        data
                    }
                }else{
                    ctx.response.status = 412;
                    ctx.body = {
                        code: 412,
                        msg: '获取用户失败',
                    }  
                }
               
              }catch(err){
                ctx.response.status = 412;
                ctx.body = {
                    code: 412,
                    msg: '获取用户失败',
                    err
                }
              }
        }else{
            ctx.response.status = 412;
                ctx.body = {
                    code: 412,
                    msg: '输入正确的用户名或密码',
                    err
                }
        }
        
      }
    /**
     * 根据登录名获取用户
     * @param ctx
     * @returns {Promise.<void>}
     */
    static async getUserByLoginName(ctx) {
        let id = ctx.params.id;
        if (id) {
            try {
                let data = await userModel.getUserByLoginName(id);
                ctx.response.status = 200;
                ctx.body = {
                    code: 200,
                    msg: '查询成功',
                    data
                }

            } catch (err) {
                ctx.response.status = 412;
                ctx.body = {
                    code: 412,
                    msg: '查询失败',
                    err
                }
            }
        } else {
            ctx.response.status = 416;
            ctx.body = {
                code: 416,
                msg: '登录名必须传'
            }
        }
    }
    /**
     * 更新用户记录
     */
    static async updatedUser (ctx) {
        let req = ctx.request.body;
        if(req.id){
            try {
                
                let olddata = await userModel.getUserByID(req.id);
                let id =req.id;
                let username =req.username ||olddata.username;
                let loginname =req.loginname ||olddata.loginname;
                let password =req.password ||olddata.password;
                let phone =req.phone ||olddata.phone;
                let iconUrl =req.iconUrl ||olddata.iconUrl;    
                let data = await userModel.updateUser(id,username, 
                    loginname, 
                    password,
                    phone,
                    iconUrl);
                ctx.response.status = 200;
                ctx.body = {
                    code: 200,
                    msg: '更新成功',
                    data
                }

            } catch (err) {
                ctx.response.status = 412;
                ctx.body = {
                    code: 412,
                    msg: '更新失败',
                    data
                }
            }
        } else {
            ctx.response.status = 416;
            ctx.body = {
                code: 416,
                msg: '更新失败（没有ID）'
            }
        }
    }
    static async deleteUserById(ctx){
        let id = ctx.params.id;
        if(id){
            try {
                let data = await userModel.deleteUserById(id);
                ctx.response.status = 200;
                ctx.body = {
                    code: 200,
                    msg: '删除成功',
                    data
                }

            } catch (err) {
                ctx.response.status = 412;
                ctx.body = {
                    code: 412,
                    msg: '删除失败',
                    err
                }
            }
        }else{
            ctx.response.status = 416;
            ctx.body = {
                code: 416,
                msg: '删除失败（没有ID）'
            }
        }
    }
    /**获取更新时间 */
    static async  getlast(ctx){
        let time=new Object()
        try {
            let otime=await overTimeModel.getlast();
            time.otime=otime[0].dataValues.updatedAt;
            let ftime=await forgetModel.getlast();
            time.ftime=ftime[0].dataValues.updatedAt;
            let ltime=await leaveModel.getlast();
            time.ltime=ltime[0].dataValues.updatedAt;
            let ctime=await checkModel.getlast();
            time.ctime=ctime[0].dataValues.updatedAt;
            ctx.response.status = 200;
                ctx.body = {
                    code: 200,
                    msg: '获取成功',
                    time
                }
        } catch (err) {
            ctx.response.status = 412;
            ctx.body = {
                code: 412,
                msg: '获取失败',
                err
            }
            console.log(err);
        }
    }
    
    /**修改密码 */
    static async updatepsw(ctx){
        let req = ctx.request.body;
        console.log(req);
        if(req.loginname){
            try {
                let data = await userModel.updateUserpswByloginName(req.loginname,req.password);
                ctx.response.status = 200;
                ctx.body = {
                    code: 200,
                    msg: '修改成功',
                    data
                }

            } catch (err) {
                ctx.response.status = 412;
                ctx.body = {
                    code: 412,
                    msg: '修改失败',
                    err
                }
            }
        }else{
            ctx.response.status = 416;
            ctx.body = {
                code: 416,
                msg: '登录信息失效，修改失败'
            }
        }
    }
}
/**\uploads\20181212\1544577365876.jpg */
async function inituserdata() {
    var datajson = xlsx.parse(path.join(__dirname,'../')+'messa.xlsx');
    var firstSheet = datajson[1].data;
    var insertval = new Array();
    //定义实体类数组
    var checktime = new Array('id', 'loginname', 'username', 'partname','password', 'roleid', 'phone', 'iconUrl');
    var res=new Array();
    for (var i = 2; i < firstSheet.length; i++) {
        let cdata = firstSheet[i];
        let odate = new Object();
        odate[checktime[0]]=uuid.v4().replace(/\-/g,"");
        for (let j = 1; j < cdata.length; j++) {
            odate[checktime[j]] = cdata[j];
        }

        odate[checktime[4]]="123456";
        odate[checktime[5]]="0";
        odate[checktime[6]]="13012345678";
        odate[checktime[7]]="/uploads/20181212/1544577365876.jpg";
        console.log(odate);
        insertval.push(odate) 
        if (i % 1000 == 0) {
           let te= await userModel.createUsers(insertval);
           res.push(te);
           insertval.splice(0, insertval.length)
        }

        //mcheckTimeModel.createCheckTime(odate);

    }
    userModel.createUsers(insertval);
}


module.exports = userController